<template>
  <div id="contentBox">
    <el-form ref="form" :model="form" :rules="rulesForm" label-width="80px" label-position="right">
      <el-form-item ref="headImg" label="封面图" prop="headImg">
        <el-upload
          action="#"
          list-type="picture-card"
          accept=".png, .JPEG, .bmp"
          :http-request="handleAvatar"
          :before-upload="beforeAvatarUpload"
          :class="{hide:hideUpload}"
          :on-change="handleImgSuccess"
          :file-list="headImgList"
        >
          <i slot="default" class="el-icon-plus" />
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="form.valueData.avatar" alt>
            <span class="el-upload-list__item-actions">
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete" />
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handlePreview">
                <i class="el-icon-zoom-in" />
              </span>
            </span>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" maxlength="30" show-word-limit />
      </el-form-item>
      <el-form-item label="内容形式" prop="content">
        <el-radio-group v-model="form.content">
          <el-radio label="1">图文</el-radio>
          <el-radio label="2">视频</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="文章内容" prop="synopsis">
        <tinymce v-if="isShowTinyMac==true" v-model="form.synopsis" />
        <el-upload
          v-if="isShowTinyMac==false"
          class="avatar-uploader"
          action="#"
          accept=".AVI, .mov, .rmvb, .rm, .FLV, .mp4, .3GP"
          :class="{hideVideoUpload:hideVideo}"
          :on-success="handleVideoSuccess"
          :before-upload="beforeUploadVideo"
          :show-file-list="false"
        >
          <!-- v-if="videoForm.showVideoPath !='' && !videoFlag" -->
          <!-- <video
            v-if="videoForm.showVideoPath !=''"
            :src="videoForm.showVideoPath"
            class="avatar video-avatar"
            controls="controls"
          >您的浏览器不支持视频播放</video>-->
          <!-- v-else-if="videoForm.showVideoPath =='' && !videoFlag" -->
          <i v-if="videoForm.showVideoPath ==''" class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
        <div v-if="videoForm.showVideoPath !=''" class="editbtn">
          <video
            :src="videoForm.showVideoPath"
            class="avatar video-avatar"
            controls="controls"
          >您的浏览器不支持视频播放</video>
          <el-button type="success" size="mini" style="margin-top:10px" @click="replaceVideo">替换</el-button>
        </div>
      </el-form-item>
      <el-form-item class="saveBtn">
        <el-button type="primary" @click="submitForm('form')">保存</el-button>
        <!-- <el-button type="primary" @click="cancelSave">退出</el-button> -->
      </el-form-item>
    </el-form>
    <!-- 图片裁剪 -->
    <el-dialog
      title="裁剪图片"
      :visible.sync="cropper.dialog"
      width="450px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
    >
      <div style="width:400px;height:400px;text-align:center;">
        <VueCropper
          ref="cropper"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          :info="true"
          :full="option.full"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :original="option.original"
          :auto-crop="option.autoCrop"
          :fixed="option.fixed"
          :fixed-number="option.fixedNumber"
          :center-box="option.centerBox"
          :info-true="option.infoTrue"
          :fixed-box="option.fixedBox"
        />
      </div>
      <div slot="footer" class="dialog-footer footer">
        <!-- <el-button @click="cropper.dialog = false">取 消</el-button> -->
        <el-button type="primary" @click="confirmCropper">确定裁剪</el-button>
      </div>
    </el-dialog>
    <el-dialog title="预览封面" :visible.sync="preciewDialogVisible">
      <img width="100%" :src="form.valueData.avatar">
    </el-dialog>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import { VueCropper } from 'vue-cropper'
export default {
  name: 'AddStrategy',
  components: { Tinymce, VueCropper },
  data() {
    return {
      rulesForm: {
        headImg: [{ required: true, message: '请上传封面图', trigger: 'blur' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [
          { required: true, message: '请选择内容形式', trigger: 'change' }
        ],
        synopsis: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      form: {
        title: '', // 标题
        content: '1', // 内容资源
        synopsis: '', // 富文本绑定
        valueData: {
          avatar: '',
          phone: ''
        }
      },
      isShowTinyMac: true,
      videoFlag: false, // 是否显示进度条
      // videoUploadPercent: "", //进度条的进度，
      isShowUploadVideo: false, // 显示上传按钮
      videoForm: {
        showVideoPath: ''
      },
      cropper: {
        dialog: false,
        src:
          'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592979325958&di=95cd2f2b6fc195bab6e89fe3fb3fe629&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fblog%2F201306%2F29%2F20130629033734_XuJ5V.jpeg',
        width: 400,
        height: 400,
        aspectRatio: 1,
        fileBlob: {}
      },
      // 裁剪组件的基础配置option
      option: {
        mode: 'cover', // 图片默认渲染方式
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 裁剪生成图片的质量
        outputType: 'jpeg', // 裁剪生成图片的格式
        canScale: true, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 400, // 默认生成截图框宽度
        autoCropHeight: 400, // 默认生成截图框高度
        fixedBox: false, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [400, 400], // 截图框的宽高比例
        full: false, // 是否输出原图比例的截图
        canMoveBox: true, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: false // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      disabled: false,
      hideUpload: false, // 上传后隐藏+号防止继续上传第二张
      hideVideo: false, // 上传视频后隐藏上传框
      headImgList: [], // 封面信息数组
      paramsList: null,
      preciewDialogVisible: false
    }
  },
  // 监听图片||视频
  watch: {
    'form.content': {
      handler: function() {
        if (this.form.content === '2') {
          this.isShowTinyMac = false
        } else {
          this.isShowTinyMac = true
          this.videoForm.showVideoPath = ''
          this.hideVideo = false
        }
      }
    }
  },
  mounted() {},
  created() {},
  methods: {
    // --------------------------------------------封面-----------------------------------------
    // 移除照片
    handleRemove() {
      this.headImgList = []
      this.hideUpload = false
    },
    // 预览照片
    handlePreview() {
      this.preciewDialogVisible = true
    },
    // 上传图片成功回调
    handleImgSuccess() {
      this.$refs.headImg.clearValidate()
    },
    // upload上传图片时触发
    handleAvatar(res, fileList) {
      this.cropper.dialog = true
      this.option.img = URL.createObjectURL(res.file)
    },
    // 上传文件之前的钩子 若返回false或者Promise则停止上传
    beforeAvatarUpload(file) {
      console.log(file)
      this.paramsdata = file
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/bmp'
      // const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG、PNG 、BMP格式!')
      }
      // if (!isLt2M) {
      //   this.$message.error("图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
      return isJPG
    },
    // 确定裁剪后获取截图的blob数据
    confirmCropper() {
      this.$refs.cropper.getCropBlob((data) => {
        const raw = {
          raw: data,
          name: new Date().valueOf()
        }
        this.uploadImgToOss(raw, true)
          .then((response) => {
            this.form.valueData.avatar = response
            this.headImgList = [{ url: response }]
            this.hideUpload = true
          })
          .finally(() => {
            this.cropper.dialog = false
          })
      })
    },
    // --------------------------------------------封面-----------------------------------------
    // --------------------------------------------视频-----------------------------------------
    // 上传前回调
    beforeUploadVideo(file) {
      console.log(file)
      const params = {
        name: new Date().valueOf(),
        raw: file
      }
      this.paramsList = params
      this.uploadImgToOss(this.paramsList, true).then((res) => {
        console.log(res)
        this.videoForm.showVideoPath = res
        this.videoFlag = true
        this.hideVideo = true
      })

      // 计算多少兆
      // var fileSize = file.size / 1024 / 1024 < 50;
      // if (
      //   [
      //     "video/mp4",
      //     "video/ogg",
      //     "video/flv",
      //     "video/avi",
      //     "video/wmv",
      //     "video/rmvb",
      //     "video/mov",
      //   ].indexOf(file.type) == -1
      // ) {
      //   this.$message.error("请上传正确的视频格式");
      //   return false;
      // }
      // if (!fileSize) {
      //   this.$message.error("视频大小不能超过50MB");
      //   return false;
      // }
      this.isShowUploadVideo = false
    },
    // 进度条
    // uploadVideoProcess(event, file, fileList) {
    //   this.videoFlag = true;
    //   this.videoUploadPercent = file.percentage.toFixed(0) * 1;
    // },
    // 上传视频成功回调
    handleVideoSuccess(res, file) {
      console.log(res)
      console.log(file)

      // this.isShowUploadVideo = true;
      // this.videoFlag = false;
      // this.videoUploadPercent = 0;
      // 前台上传地址
      // if (file.status == 'success' ) {
      //    this.videoForm.showVideoPath = file.url;
      // } else {
      //    this.$message.error('"上传失败，请重新上传"')
      // }
      // 后台上传地址
      // if (res.Code == 0) {
      //   this.videoForm.showVideoPath = res.Data;
      // } else {
      //   this.$message.error("XXX");
      // }
    },
    // --------------------------------------------视频-----------------------------------------
    // 替换视频
    replaceVideo() {
      // this.isShowTinyMac = true;
      this.videoForm.showVideoPath = ''
      this.hideVideo = false
    },
    // 保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (this.headImgList.length > 0) {
          this.$refs['headImg'].clearValidate()
          this.rulesForm.headImg[0].required = false
        }
        if (valid) {
          alert('成功上传!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 退出保存
    cancelSave() {
      this.$confirm('您还没有保存信息,退出将丢失内容,确定退出吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {})
        .catch(() => {})
    }
  }
}
</script>

<style lang='scss' scoped>
#contentBox {
  padding: 20px 10px;
}
.el-input {
  width: 600px;
}
/deep/ .el-dialog__footer > .footer {
  text-align: center;
}
.hide /deep/.el-upload--picture-card {
  display: none;
  width: 100px;
  height: 100px;
}
.hideVideoUpload /deep/.el-upload--text {
  display: none;
  width: 100px;
  height: 100px;
}
.avatar-uploader {
  width: 148px;
  height: 148px;
  border: 1px dashed #c0ccda;
  background-color: #fbfdff;
  box-sizing: border-box;
  cursor: pointer;
  line-height: 146px;
  vertical-align: top;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28px !important;
  color: #8c939d !important;
}
.avatar-uploader:hover {
  border-color: #1979fe;
}
/deep/ .el-upload {
  position: relative;
  // width: 100%;
}
/deep/ .el-upload--text {
  width: 100%;
}
/deep/ .video-avatar {
  width: 150px !important;
  height: 150px !important;
  position: absolute;
  left: 0px;
  top: 0px;
}
</style>
